package com.cooba.activitys.Living;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cooba.R;
import com.cooba.upload.CustomMultipartEntity;
import com.cooba.utils.BitmapCompressor;
import com.cooba.utils.BitmapZipUtil;
import com.cooba.utils.ServerURL;
import com.cooba.utils.SharedPreferencesUtil;
import com.cooba.views.ContainsEmojiEditText;
import com.cooba.views.ProgressImageView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.ta.utdid2.android.utils.StringUtils;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import me.nereo.multi_image_selector.MultiImageSelector;

public class LivingSubjectAddActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int REQUEST_IMAGE = 0;
    protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;
    protected static final int REQUEST_STORAGE_WRITE_ACCESS_PERMISSION = 102;

    private ImageButton my_living_add_subject_image_back;
    private ContainsEmojiEditText my_living_add_subject_title_et;
    private ImageView my_living_add_subject_add_image_iv1;
    private ImageView my_living_add_subject_add_image_iv2;
    private TextView my_living_add_subject_create_tv;
    private RelativeLayout my_living_add_subject_add_image_rl;
    private HttpUtils httpUtils;
    private RequestParams params;
    private String livie_id;
    private Dialog dialog;
    private LayoutInflater li;
    private ProgressImageView imageView;
    private TextView upload_image_progress_tv;
    private int i = 0;
    private ArrayList<String> mSelectPath = new ArrayList<>();
    private ArrayList<File> fileList = new ArrayList<>();
    private HttpMultipartPost post;
    private StringBuilder sburl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_living_add_subject);
        initView();
        initListener();
    }

    private void initListener() {
        my_living_add_subject_image_back.setOnClickListener(this);
        my_living_add_subject_create_tv.setOnClickListener(this);
        my_living_add_subject_add_image_iv1.setOnClickListener(this);
        my_living_add_subject_add_image_iv2.setOnClickListener(this);
    }

    private void initView() {
        my_living_add_subject_image_back = (ImageButton) findViewById(R.id.my_living_add_subject_image_back);
        my_living_add_subject_title_et = (ContainsEmojiEditText) findViewById(R.id.my_living_add_subject_title_et);
        my_living_add_subject_add_image_iv1 = (ImageView) findViewById(R.id.my_living_add_subject_add_image_iv1);
        my_living_add_subject_add_image_iv2 = (ImageView) findViewById(R.id.my_living_add_subject_add_image_iv2);
        my_living_add_subject_create_tv = (TextView) findViewById(R.id.my_living_add_subject_create_tv);
        my_living_add_subject_add_image_rl = (RelativeLayout) findViewById(R.id.my_living_add_subject_add_image_rl);
        int width = getResources().getDisplayMetrics().widthPixels;
        int height = (int) (width * 0.56);
        my_living_add_subject_add_image_rl.setLayoutParams(new LinearLayout.LayoutParams(width, height));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.my_living_add_subject_image_back:
                finish();
                break;
            case R.id.my_living_add_subject_add_image_iv1:
                pickImage();
                break;
            case R.id.my_living_add_subject_add_image_iv2:
                pickImage();
                break;
            case R.id.my_living_add_subject_create_tv:
                if (TextUtils.isEmpty(my_living_add_subject_title_et.getText().toString().toString())) {
                    Toast.makeText(this, "请输入直播名称!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (fileList.size() <= 0) {
                    Toast.makeText(this, "请上传图片!", Toast.LENGTH_SHORT).show();
                    return;
                }

                doCreate();
                break;
            default:
                break;
        }
    }

    private void pickImage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
                    getString(R.string.mis_permission_rationale),
                    REQUEST_STORAGE_READ_ACCESS_PERMISSION);
        }
        {
            MultiImageSelector.create(LivingSubjectAddActivity.this)
                    .showCamera(true) // 是否显示相机. 默认为显示
                    .count(1) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效
                    .single() // 多选模式, 默认模式;
                    .start(LivingSubjectAddActivity.this, REQUEST_IMAGE);
        }
    }

    private void requestPermission(final String permission, String rationale, final int requestCode) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            new AlertDialog.Builder(this)
                    .setTitle(R.string.mis_permission_dialog_title)
                    .setMessage(rationale)
                    .setPositiveButton(R.string.mis_permission_dialog_ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(LivingSubjectAddActivity.this, new String[]{permission}, requestCode);
                        }
                    })
                    .setNegativeButton(R.string.mis_permission_dialog_cancel, null)
                    .create().show();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_STORAGE_READ_ACCESS_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                pickImage();
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                mSelectPath.clear();
                mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                StringBuilder sb = new StringBuilder();
                for (String p : mSelectPath) {
                    sb.append(p);
                    sb.append("\n");
                }

                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                Bitmap btemp = BitmapFactory.decodeFile(mSelectPath.get(0), options);
                if (options.outWidth > options.outHeight) {
                    showUploadDialog();
                } else {
                    Toast.makeText(LivingSubjectAddActivity.this, "请上传宽图!", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private void doCreate() {
        httpUtils = new HttpUtils();
        params = new RequestParams();
        String login_id = SharedPreferencesUtil.getData(this, "login_id", "");
        String name = SharedPreferencesUtil.getData(this, "name", "");
        params.addBodyParameter("name", my_living_add_subject_title_et.getText().toString().trim());
        params.addBodyParameter("sort_id", "");
        params.addBodyParameter("pic", sburl.toString());
        params.addBodyParameter("user_id", login_id);
        params.addBodyParameter("user_name", name);
        String urlcreatemyliving = ServerURL.httpUrl + ServerURL.createmyliving;
        httpUtils.send(HttpRequest.HttpMethod.POST, urlcreatemyliving, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.d("wei", "创建直播成功" + responseInfo.result);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(responseInfo.result.toString());
                    String status = jsonObject.get("status").toString();
                    if (status.equals("1")) {

                        setResult(RESULT_OK);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Log.d("wei", "创建直播失败" + msg);
            }
        });
    }

    private void showUploadDialog() {
        dialog = new Dialog(this);
        li = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View v = li.inflate(R.layout.dialog_upload_image, null);
        android.view.Window window = dialog.getWindow();
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(v);
        dialog.setCanceledOnTouchOutside(false);
        //window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
        window.setBackgroundDrawableResource(android.R.color.transparent);
        window.setGravity(Gravity.CENTER);
        dialog.show();
        imageView = (ProgressImageView) v.findViewById(R.id.upload_image_progress_iv);
        upload_image_progress_tv = (TextView) v.findViewById(R.id.upload_image_progress_tv);
        TextView cancel = (TextView) v.findViewById(R.id.upload_image_progress_cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (post.isCancelled()) {
                    post.cancel(true);
                }
            }
        });
        fileList.clear();
        i = 0;
        for (int i = 0; i < mSelectPath.size(); i++) {
            File file = BitmapZipUtil.scal(mSelectPath.get(i), LivingSubjectAddActivity.this);
            fileList.add(file);
        }
//        for (int i=0;i<mSelectPath.size();i++){
//            Bitmap bitmap=BitmapCompressor.decodeSampledBitmapFromFile(mSelectPath.get(i),300,800);
//
//        }

        Bitmap bitmap = BitmapFactory.decodeFile(fileList.get(0).getPath());
        imageView.setImageBitmap(bitmap);
        sburl = new StringBuilder();
        upload();
    }


    private void upload() {
        post = new HttpMultipartPost(LivingSubjectAddActivity.this, fileList.get(i).getPath(), ServerURL.httpUrl + ServerURL.uploadImg);
        post.execute();
    }

    class HttpMultipartPost extends AsyncTask<String, Integer, String> {

        private Context context;
        private String filePath;
        //private ProgressDialog pd;
        private long totalSize;
        private String requestUrl;

        public HttpMultipartPost(Context context, String filePath, String requestUrl) {
            this.context = context;
            this.filePath = filePath;
            this.requestUrl = requestUrl;
        }

        @Override
        protected void onPreExecute() {
            upload_image_progress_tv.setText("正在上传(" + (i + 1) + "/" + fileList.size() + ")");
        }

        @Override
        protected String doInBackground(String... params) {
            String serverResponse = null;
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext httpContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(requestUrl);

            try {
                CustomMultipartEntity multipartContent = new CustomMultipartEntity(
                        new CustomMultipartEntity.ProgressListener() {
                            @Override
                            public void transferred(long num) {
                                publishProgress((int) ((num / (float) totalSize) * 100));
                            }
                        });

                // 使用FileBody上传图片
                multipartContent.addPart("value", new FileBody(new File(filePath)));
                totalSize = multipartContent.getContentLength();
                // 上传
                httpPost.setEntity(multipartContent);
                HttpResponse response = httpClient.execute(httpPost, httpContext);
                serverResponse = EntityUtils.toString(response.getEntity());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return serverResponse;
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            imageView.setProgress((int) (progress[0]));
        }

        @Override
        protected void onPostExecute(String result) {
            System.out.println("result: " + result);
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(result.toString());
                String status = jsonObject.get("status").toString();
                if (status.equals("1")) {
                    String url = jsonObject.get("url").toString();
                    sburl.append(url);
                    sburl.append("#");
                    i++;
                    if (i < fileList.size()) {
                        upload();
                    } else {
                        dialog.dismiss();
                        Bitmap bitmap = BitmapFactory.decodeFile(fileList.get(0).getPath());
                        my_living_add_subject_add_image_iv1.setVisibility(View.GONE);
                        my_living_add_subject_add_image_iv2.setVisibility(View.VISIBLE);
                        int width = context.getResources().getDisplayMetrics().widthPixels;
                        int height = (int) (width * 0.56);
                        my_living_add_subject_add_image_iv2.setLayoutParams(new RelativeLayout.LayoutParams(width, height));
                        my_living_add_subject_add_image_iv2.setImageBitmap(bitmap);
                    }
                } else {
                    Toast.makeText(LivingSubjectAddActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected void onCancelled() {
            System.out.println("cancle");
        }

    }

}
